﻿// // ******************************************************************
// //       /\ /|       @file       CacheKeyQueryHandler.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-02-22 20:02
// //    *(__\_\        @Copyright  Copyright (c) , 2025-02-04 14:02 Await
// // ******************************************************************

using AutomaticSubtitles.Contracts.Dto;
using AutomaticSubtitles.Service.Application.Cahce.Queries;
using AutomaticSubtitles.Service.DataAccess.Model;
using AutomaticSubtitles.Service.Domain.Config;
using static AutomaticSubtitles.Service.Infrastructure.Configuration.GlobalVariableEnumConfiguration;

namespace AutomaticSubtitles.Service.Application.Cahce;

public class CacheKeyQueryHandler(ICacheKeyRepository _repository, ILogger<CacheKeyQueryHandler> logger) : BaseAutoService
{
    [EventHandler]
    public async Task Handle(GetCacheKeyListQuery command)
    {
        var countAsync = await _repository.FindAsync(x => x.IsShow == true);
        command.Result = countAsync?.MapToList<CacheKeyDto>();
    }

    [EventHandler]
    public async Task Handle(GetCachePathList command)
    {
        IReadOnlyList<string>? tvPlayResult = null;
        IReadOnlyList<string>? result = null;
        var data = await _repository.GetListAsync(x => (x.Key == CacheCommon.CacheTVKey || x.Key == CacheCommon.CacheMovieKey) && x.IsShow == true);
        foreach (var item in data)
            if (item.Key == CacheCommon.CacheMovieKey)
                result = item.Value.Split('\n').ToList();
            else if (item.Key == CacheCommon.CacheTVKey) tvPlayResult = item.Value.Split('\n').ToList();
        var noData = await _repository.GetListAsync(x => x.Key == CacheCommon.CacheNoKey && x.IsShow == true);
        command.NoCachePath = noData.SelectMany(x => x.Value.Split('\n')).ToList();
        command.TVPlayResult = tvPlayResult;
        command.Result = result;
    }

    [EventHandler]
    public async Task Handle(GetPublicTranslationDataAddressQuery command)
    {
        var autoCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.PublicCacheData);
        if (autoCacheKey != null)
            command.Result = autoCacheKey.Value.Split('\n').ToList();
    }

    [EventHandler]
    public async Task Handle(GetModifyPromptWordQuery command)
    {
        var autoCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.AiConfigPromptWord);
        command.Result = autoCacheKey?.Value ?? PromptWord;
    }

    [EventHandler]
    public async Task Handle(GetCacheKeyGetMediaDirectoryConfigurationListQuery command)
    {
        // || (x.Key == CacheCommon.CacheMovieKey && x.IsShow == true);
        var autoCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.CacheTVKey);
        var mvCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.CacheMovieKey);
        var noCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.CacheNoKey);
        var data = new MediaConfigurationDto
        {
            SeriesPath = autoCacheKey?.MapTo<CacheKeyDto>(),
            FilmPath = mvCacheKey?.MapTo<CacheKeyDto>(),
            ExcludePath = noCacheKey?.MapTo<CacheKeyDto>()
        };
        command.Result = data;
    }

    [EventHandler]
    public async Task Handle(GetAiConfigQuery query)
    {
        var configCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.AiConfigValue);
        var config = await _repository.FindAsync(x => x.Key == CacheCommon.AiConfig);
        try
        {
            query.Enabled = Convert.ToBoolean(configCacheKey.SecondaryValue);
        }
        catch (Exception e)
        {
        }

        query.Model = configCacheKey?.Value;
        query.Path = config?.SecondaryValue;
        query.Result = config?.Value;
    }

    [EventHandler]
    public async Task Handle(GetCacheKeyBaiduTranslationAPIConfigurationQuery command)
    {
        // || (x.Key == CacheCommon.CacheMovieKey && x.IsShow == true);
        var autoCacheKey = await _repository.FindAsync(x => x.Key == CacheCommon.BaiduTranslateApiKey);
        IsDataNotExist(autoCacheKey);
        var data = new BaiduTranslationAPIDto
        {
            Id = autoCacheKey!.Id,
            AppId = autoCacheKey.Value,
            SecretKey = autoCacheKey.SecondaryValue ?? ""
        };
        command.Result = data;
    }

    [EventHandler]
    public async Task Handle(GetCacheTaskListQuery command)
    {
        var autoCacheKeys = await _repository.GetListAsync(x => x.IsShow == true && x.Key == CacheCommon.CacheTaskKey);
        var data = autoCacheKeys.Select(item => new TaskDto() { Name = item.Value, Value = item.SecondaryValue! }).ToList();
        command.Result = data;
    }

    [EventHandler]
    public async Task Handler(FirstAIQuery query)
    {
        var ordering = await _repository.GetListAsync(x => x.IsShow == true && x.Key == CacheCommon.Configordering, "Sort", false);
        query.Result = ordering.FirstOrDefault()?.Value == TranslationConfigurationEnum.AI.ToString();
    }

    [EventHandler]
    public async Task Handle(GetConfigorderingQuery query)
    {
        var ordering = await _repository.GetListAsync(x => x.IsShow == true && x.Key == CacheCommon.Configordering);
        var data = ordering.ToList();
        if (data.Count == 0)
        {
            data.Add(new Auto_CacheKey(BasicsHelper.GetId())
            {
                Name = CacheCommon.Configordering,
                Key = CacheCommon.Configordering,
                Value = TranslationConfigurationEnum.AI.ToString(),
                GroupName = "优先排序",
                IsShow = true,
                Sort = 1,
                CreateTime = DateTime.Now
            });
            data.Add(
                new Auto_CacheKey(BasicsHelper.GetId())
                {
                    Name = CacheCommon.Configordering,
                    Key = CacheCommon.Configordering,
                    Value = TranslationConfigurationEnum.Baidu.ToString(),
                    GroupName = "优先排序",
                    IsShow = true,
                    Sort = 2,
                    CreateTime = DateTime.Now
                });
            await _repository.AddRangeAsync(data);
        }

        query.Result = data.OrderBy(x => x.Sort).Select(x => new BasicsSelectDto<int>()
        {
            Id = x.Id,
            Label = x.Value,
            Value = Convert.ToInt32(Enum.Parse<TranslationConfigurationEnum>(x.Value))
        }).ToList();
    }
}